<template>
  <a-layout style="min-height: 100vh;">
    <a-layout-sider class="full-height-sider" width="300">
      <Sider />
    </a-layout-sider>
    <a-layout class="full-page-layout">
      <a-layout-header class="layout-header">
        <div class="header-content">
          <div style="font-size: 18px; font-weight: 500;">AI聊天室</div>
        </div>
      </a-layout-header>
      <a-layout-content class="layout-content">
        <div ref="chatContainer" style="width: 80%; max-width: 800px; height: 100%; overflow-y: auto; padding: 20px; box-sizing: border-box; border: 1px solid #e5e6eb; border-radius: 12px; background-color: #fff;">
          <!-- 初始问候语 - 修复显示逻辑 -->
          <div class="message ai-message" v-if="(!userStore.currentConversation.conversationId || isNewConversation) && messages.length === 0">
            <div class="message-content">
              {{ welcomeText }}
              <template v-if="isWelcomeTyping">
                <span class="typing-indicator">
                  <span>.</span><span>.</span><span>.</span>
                </span>
              </template>
            </div>
          </div>

          <!-- 聊天消息列表 -->
          <div class="message-list">
            <template v-for="msg in messages" :key="msg.id">
              <!-- 用户消息 -->
              <div v-if="msg.role === 'user'" class="message user-message">
                <div class="message-content">
                  {{ msg.displayText }}
                  <template v-if="msg.fileName">
                    <div style="margin-top: 5px; color: #666; font-size: 12px;">
                      📎 {{ msg.fileName }}
                    </div>
                  </template>
                </div>
              </div>

              <!-- AI消息 -->
              <div v-if="msg.role === 'ai'" class="message ai-message">
                <div class="message-content">
                  {{ msg.displayText }}
                  <template v-if="msg.isTyping">
                    <span class="typing-indicator">
                      <span>.</span><span>.</span><span>.</span>
                    </span>
                  </template>
                </div>
              </div>
            </template>
          </div>
        </div>
      </a-layout-content>
      <a-layout-footer class="layout-footer">
        <div style="width: 80%; max-width: 800px; padding: 20px; box-sizing: border-box; border: 1px solid #e5e6eb; border-radius: 12px; background-color: #fff;">
          <!-- 文本输入区域 -->
          <div style="margin-bottom: 15px;">
            <a-textarea
                v-model:value="input"
                :bordered="false"
                placeholder="请输入消息，按Enter发送，支持上传文件"
                :auto-size="{ minRows: 3, maxRows: 5 }"
                style="width: 100%; padding-right: 45px"
                @keydown="handleKeyPress"
            />
          </div>

          <!-- 按钮区域 -->
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                :limit="1"
                :on-change="handleFileChange"
                :auto-upload="false"
                :disabled="!userStore.islogin||isLoading"
            >
              <a-tooltip
                  :title="!userStore.islogin ? '需要登录才能上传文件' : ''"
                  :disabled="userStore.islogin"
              >
                <a-button
                    type="primary"
                    :disabled="!userStore.islogin||isLoading"
                >
                  <upload-outlined />
                  上传文件
                </a-button>
              </a-tooltip>
            </el-upload>

            <a-button
                type="primary"
                shape="circle"
                :icon="isLoading ? h(SendOutlined, { spin: true }) : h(ArrowUpOutlined)"
                :style="{
          fontSize: '16px',
          width: '36px',
          height: '36px'
        }"
                @click="sendMessage(userStore.user.userId)"
                :disabled="isLoading"
            />
          </div>
        </div>
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, onMounted, onUnmounted, h, watch } from 'vue';
import { ArrowUpOutlined, SendOutlined } from '@ant-design/icons-vue';
import { UploadOutlined } from '@ant-design/icons-vue/lib/icons';
import { ElMessage } from "element-plus";
import { useUserStore } from '@/store/usersStore.js';
import Sider from './Sider.vue';

const userStore = useUserStore();

type Message = {
  id: string;
  text: string;
  displayText: string;
  role: 'user' | 'ai';
  isTyping: boolean;
  fileName?: string;
  typingTimer?: number;
};

// 新增：标记是否为新对话
const isNewConversation = ref(true);
const welcomeFullText = '我是你的AI助手，有什么问题可以尽管问我，支持文本和文件提问哦~';
const welcomeText = ref('');
const isWelcomeTyping = ref(true);
const messages = reactive<Message[]>([]);
const input = ref('');
const chatContainer = ref<HTMLDivElement | null>(null);
const isLoading = ref(false);
const uploadRef = ref<any>();
const selectedFile = ref<File | null>(null);

const generateId = (role: 'user' | 'ai') => {
  return `${role}_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
};

const initWelcome = () => {
  // 重置欢迎语
  welcomeText.value = '';
  isWelcomeTyping.value = true;

  let index = 0;
  const timer = setInterval(() => {
    if (index >= welcomeFullText.length) {
      clearInterval(timer);
      isWelcomeTyping.value = false;
      return;
    }
    welcomeText.value += welcomeFullText[index];
    index++;
    scrollToBottom();
  }, 20);
};

const handleFileChange = (file: any) => {
  if (file.status === 'ready') {
    selectedFile.value = file.raw;
    ElMessage.success(`已选择文件: ${file.name}`);
  } else if (file.status === 'exceed') {
    ElMessage.warning('最多只能上传1个文件');
  }
};

// 监听历史消息变化，更新当前聊天消息
watch(
    () => userStore.historyMessages,
    (newMessages) => {
      if (newMessages && newMessages.length > 0) {
        // 有历史消息，不是新对话
        isNewConversation.value = false;
        // 清空现有消息
        messages.length = 0;

        // 转换历史消息格式并添加到当前消息列表
        newMessages.forEach(msg => {
          messages.push({
            id: msg.id,
            text: msg.text,
            displayText: msg.text,
            role: msg.sender === 'user' ? 'user' : 'ai',
            isTyping: false,
            fileName: msg.fileName
          });
        });

        // 滚动到底部
        scrollToBottom();
      } else if (userStore.currentConversation.conversationId) {
        // 有对话ID但没有消息，视为新对话
        isNewConversation.value = true;
        messages.length = 0;
        // 显示欢迎语
        initWelcome();
      }
    },
    { deep: true }
);

// 监听对话切换
watch(
    () => userStore.currentConversation.conversationId,
    (newId, oldId) => {
      // 当切换到新的对话ID且不是初始状态时
      if (newId && newId !== oldId) {
        // 检查是否有历史消息
        if (!userStore.historyMessages || userStore.historyMessages.length === 0) {
          isNewConversation.value = true;
          // 显示欢迎语
          initWelcome();
        } else {
          isNewConversation.value = false;
        }
      } else if (!newId) {
        // 没有对话ID，显示欢迎语
        isNewConversation.value = true;
        initWelcome();
      }
    }
);

// 监听消息变化，当有消息时隐藏欢迎语
watch(
    () => messages.length,
    (length) => {
      if (length > 0) {
        isNewConversation.value = false;
      }
    }
);

onMounted(() => {
  initWelcome();
});

onUnmounted(() => {
  messages.forEach(msg => {
    if (msg.typingTimer) {
      clearInterval(msg.typingTimer);
    }
  });
});

const typeMessage = (msg: Message, fullText: string) => {
  if (msg.typingTimer) {
    clearInterval(msg.typingTimer);
  }
  let index = 0;
  msg.text = fullText;
  msg.displayText = '';
  msg.isTyping = true;
  const typingSpeed = 20;
  msg.typingTimer = window.setInterval(() => {
    const exists = messages.some(m => m.id === msg.id);
    if (!exists) {
      clearInterval(msg.typingTimer);
      return;
    }
    if (index < fullText.length) {
      msg.displayText += fullText[index];
      index++;
      scrollToBottom();
    } else {
      clearInterval(msg.typingTimer);
      msg.typingTimer = undefined;
      msg.isTyping = false;
      scrollToBottom();
    }
  }, typingSpeed);
};

const sendMessage = async (userId:any) => {
  console.log("===== 开始发送用户消息 =====");

  if (await userStore.isneedlogin() === false) {
    console.log("用户未登录，终止发送");
    return;
  }

  const userInputText = input.value.trim();
  if (!userInputText) {
    ElMessage.warning('请输入文本');
    return;
  }

  // 发送消息后标记为非新对话
  isNewConversation.value = false;

  const userMessage: Message = {
    id: generateId('user'),
    text: userInputText,
    displayText: userInputText,
    role: 'user',
    isTyping: false,
    fileName: selectedFile.value?.name
  };
  messages.push(userMessage);
  input.value = '';
  scrollToBottom();

  const aiMessage: Message = {
    id: generateId('ai'),
    text: '',
    displayText: '',
    role: 'ai',
    isTyping: true
  };
  messages.push(aiMessage);
  scrollToBottom();

  try {
    isLoading.value = true;
    const formData = new FormData();
    formData.append('text', userInputText);
    formData.append('userId', userStore.user.userId.valueOf());

    // 添加当前对话ID
    if (userStore.currentConversation.conversationId) {
      formData.append('conversationId', userStore.currentConversation.conversationId);
    }

    if (selectedFile.value) {
      formData.append('file', selectedFile.value);
    }

    if(userInputText.length<=8) {
      await userStore.newConversation(userStore.user.userId, userInputText);
    }else{
      await userStore.newConversation(userStore.user.userId, userInputText.substring(0,8)+'....');
    }
    const response = await fetch(
        'ai/messages/sendmessage',
        { method: 'POST', body: formData }
    );

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const reader = response.body?.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (reader) {
      const { done, value } = await reader.read();
      if (done) break;

      const decoded = decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
      buffer += decoded;

      let lastIndex = 0;
      while (lastIndex < buffer.length) {
        const eolIndex = buffer.indexOf('\n\n', lastIndex);
        if (eolIndex === -1) break;

        const sseLine = buffer.substring(lastIndex, eolIndex).trim();
        lastIndex = eolIndex + 2;

        if (!sseLine || !sseLine.startsWith('data:')) continue;

        // 增强清洗：移除所有可能的data:变体
        let content = '';
        if (sseLine.length >= 5) {
          content = sseLine.slice(5).trim()
              // 匹配任何形式的data:（包括大小写、空格、重复）
              .replace(/(data:?\s*)+/g, '')
              // 额外处理可能的残留空格
              .replace(/\s+/g, ' ').trim();
        } else {
          content = sseLine.trim().replace(/(data:?\s*)+/g, '');
        }

        if (content) {
          const aiIndex = messages.findIndex(m => m.id === aiMessage.id);
          if (aiIndex !== -1) {
            messages[aiIndex].displayText += content;
            scrollToBottom();
          }
        }
      }
      buffer = buffer.substring(lastIndex);
    }

    const aiIndex = messages.findIndex(m => m.id === aiMessage.id);
    if (aiIndex !== -1) {
      messages[aiIndex].text = messages[aiIndex].displayText;
      messages[aiIndex].isTyping = false;
    }

  } catch (error) {
    console.error('请求错误:', error);
    const aiIndex = messages.findIndex(m => m.id === aiMessage.id);
    if (aiIndex !== -1) {
      messages[aiIndex].displayText = '抱歉，请求过程中发生错误，请稍后重试';
      messages[aiIndex].text = messages[aiIndex].displayText;
      messages[aiIndex].isTyping = false;
    }
    ElMessage.error('网络错误或服务器异常');
  } finally {
    isLoading.value = false;
    if (uploadRef.value?.clearFiles) uploadRef.value.clearFiles();
    selectedFile.value = null;
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    chatContainer.value?.scrollTo({
      top: chatContainer.value.scrollHeight,
      behavior: 'smooth'
    });
  });
};

const handleKeyPress = (e: KeyboardEvent) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    sendMessage(userStore.user.userId);
  }
};
</script>





<style scoped>
/* 样式保持不变 */
.message-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-top: 16px;
}

.message {
  max-width: 100%;
  display: flex;
  margin-bottom: 10px;
}

.user-message { justify-content: flex-end; }
.ai-message { justify-content: flex-start; }

.message-content {
  padding: 12px 16px;
  border-radius: 12px;
  max-width: 80%;
  word-wrap: break-word;
  line-height: 1.5;
}

.user-message .message-content {
  background-color: #1677ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-content {
  color: #333;
  background-color: #f0f2f5;
  border-bottom-left-radius: 4px;
}

.typing-indicator {
  display: inline-block;
  margin-left: 8px;
}

.typing-indicator span {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin: 0 1px;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

/* 布局样式 */
.full-page-layout {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.layout-header {
  flex: 0 0 10%;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.layout-content {
  flex: 1 1 70%;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}

.layout-footer {
  flex: 0 0 20%;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.full-height-sider {
  height: 100vh;
  background-color: grey;
  border-right: 1px solid lightgrey;
}
</style>